Ext.onReady(function()
{ 

    Ext.QuickTips.init();
	//查询输入条件
    var itemsPerPage = 10; 
	var formSearch = Ext.create('Ext.form.Panel', {
		  id:'formSearch',
		  collapsible: true,
		  url: 'ExtAction!searchByCondition', 
		  bodyStyle: 'padding:5px 5px 5px',
		  frame : true,
		  //height:'20%',
		  //layout:'fit',
		  heigth:100,
		  border:true,
		  region : "north",
		  defaultType: 'textfield',
	      fieldDefaults: {
	            labelWidth: 55,
	            labelAlign:'right'
	        },
		  layout: {type: 'table', columns: 3},
          items :[{fieldLabel: 'id',id:'ids',name: 'id'}, 
				  {fieldLabel: 'name',id:'names',name: 'name'},
				  {fieldLabel: 'account',id:'ages',name: 'account'},
				  {fieldLabel: 'password',id:'emails',name: 'password'}//,vtype:'password' 
				 ],
		  buttons:[ '->',{text:"查询",formBind: true,disabled: false,
                      handler: function() {  store.load(); }
                    },
                    {text:"重置",handler: function() {formSearch.getForm().reset();}}
                 ]
	 });
	
	
//数据存储 
    //数据模型 
	Ext.define('User', {
	    extend: 'Ext.data.Model',
	    fields: [
		         { name: 'id', type: 'int' },
		         { name: 'account', type: 'string' },
		         { name: 'name', type: 'string' },
		         { name: 'password', type: 'string' }
	    	    ]
	   });
//静态假数据 
/* var store = Ext.create('Ext.data.Store', {
	 //storeId:'simpsonsStore', 
	      params:{start:0, limit: itemsPerPage },
          fields:['id','name','account','password'],
		  data:{'items':[{"id":"1","name":"Lisa","account":"23", "password":"12345678"},
		                 {"id":"2","name":"Lisa","account":"23", "password":"12345678"},                              
		                 {"id":"3","name":"Lisa","account":"23", "password":"12345678"},                              
		                 {"id":"4","name":"Lisa","account":"23", "password":"12345678"},                             
		                 {"id":"5","name":"Lisa","account":"23", "password":"12345678"},                             
		                 {"id":"6","name":"Lisa","account":"23", "password":"12345678"},                             
		                 {"id":"7","name":"Lisa","account":"23", "password":"12345678"},                             
		                 {"id":"8","name":"Lisa","account":"23", "password":"12345678"},                             
		                 {"id":"9","name":"Lisa","account":"23", "password":"12345678"},                             
		                 {"id":"10","name":"Lisa","account":"23", "password":"12345678"},                             
		                 {"id":"11","name":"Lisa","account":"23", "password":"12345678"},                             
		                 {"id":"12","name":"Lisa","account":"23", "password":"12345678"},                             
		                 {"id":"13","name":"Lisa","account":"23", "password":"12345678"}                            
		       		    ]},    
		  proxy: {type: 'memory',reader: {type: 'json',root: 'items'}}});*/ 
//从后台获取数据 
   //数据存储 
	var store = Ext.create('Ext.data.Store', {
	    //storeId:'simpsonsStore',
	    model: 'User',
	    pageSize: 15,
	    proxy: {
	        type: 'ajax',
	        url: 'searchUsers',
	        //reader: 'json'
		    reader: {
		             type : 'json',
	                 root:'rows',
	                 totalProperty:'count'
	                }
	       /*extraParams:{
	    	    id:Ext.getCmp('formSearch').getForm().findField('id').getValue(),
	    	    name:Ext.getCmp('name').getValue(),
	    	    account:Ext.getCmp('account').getValue(),
	    	    password:Ext.getCmp('password').getValue()	    	    	
	    },*/
	    },
	     //id:formSearch.getForm().findField('id').getValue(),
	   // params:{start:0, limit: 1 },
	    autoLoad: true
	  });
	//数据初始化Load
	//store.setDefaultSort('id', 'ASC');
	// 这里很关键，如果不加，翻页后搜索条件就变没了，这里的意思是每次数据载入前先把搜索表单值加上去，这样就做到了翻页保留搜索条件了
	store.on('beforeload', function() {
		Ext.apply(this.proxy.extraParams, {
			   id:formSearch.getForm().findField('id').getValue(),
	           name:formSearch.getForm().findField('name').getValue(),
	           account:formSearch.getForm().findField('account').getValue(),
	           password:formSearch.getForm().findField('password').getValue()
		});
	});
	 /*store.on('beforeload', function (store, options) {
        var new_params = { id:formSearch.getForm().findField('id').getValue(),
				           name:formSearch.getForm().findField('name').getValue(),
				           account:formSearch.getForm().findField('account').getValue(),
				           password:formSearch.getForm().findField('password').getValue()        					
        	             };
        Ext.apply(store.proxy.extraParams, new_params);
        // alert('beforeload');
    });
	store.load();*/
	
	//编辑form 
	var editform = Ext.create('Ext.form.Panel',{
		  id:'formAdd',
		  url: 'editUser',       
		  bodyStyle:'padding:10px 5px 0', 
		  frame:false,
		  border:false,
		  fieldDefaults: {
	            labelAlign:'right',
	            labelWidth: 50,
	            msgTarget: 'side' //验证提示信息位置 
	        },   
		  defaults: {bodyPadding: 4},
		  defaultType: 'textfield',
		  layout: {type: 'table', columns: 2},//表格布局排列文本 框  
          items :[{fieldLabel: 'id',name: 'id',hidden:false},
        	      {fieldLabel: 'name',name: 'name',allowBlank:false},
				  {fieldLabel: 'account',name: 'account'},
				  {fieldLabel: 'password',name: 'password'},//,vtype:'password' 
				  {fieldLabel: 'formmode',id:'formmode',name: 'formmode',hidden:true} 
				 ],
		  buttons:[ {text:"保存",handler: function() {
                                                if (editform.getForm().isValid())
                                                  { 
                                                	editform.getForm().submit(
                                                            {success: function(editform,action){
                                                            			alert(action);
                                                            			alert(action.result.msg);
                                                    					Ext.Msg.alert('success',action.result.msg);
                                                    					editwin.hide();
                                                  						grid1.store.load();
                                                  						},
                                                             failure: function(){ 
                                                                       Ext.Msg.alert('failed', action.result.msg);}
                                                            });
                                                   } else {
												} 
                                                }
                 },
                 {text:"重置",handler: function() {editform.getForm().reset();}}
                ]
	});

   //编辑弹出窗口
	var editwin= Ext.create('Ext.Window', {
		id:'add',
		title :'edit',
		layout :'fit',
		width : 500,
		height : 300,			//默认是close
		closeAction: 'hide', 	//这里一定记得要有哦，如果是点窗口的X关闭，没有这个是不能重复关闭的。
		plain:true,//布尔类型，true表示强制与背景色保持协调，默认值为false。
		border : true,
		modal : true,
		draggable : true,
		constrain : true,
		items:[editform]
	});
   
   //菜单项 Action
	 var addAction = Ext.create('Ext.Action', {
		text: 'Add',
        //icon   : '../shared/icons/fam/delete.gif',  // Use a URL in the icon config
        iconCls:'icon-add',
        tooltip:'Add a new row',
        disabled: false,
        handler: function() {
        	editform.getForm().reset();
			Ext.getCmp('formmode').setValue('add');
			editwin.setTitle('添加');
			editwin.show();
        }
    });
   
   var updateAction = Ext.create('Ext.Action', {       
        text: 'Update',
        iconCls:'icon-edit',
        tooltip:'update the selected item',
        disabled: true,
        handler: function(view, record, item,index, e, options) {
            var record = grid1.getSelectionModel().getSelection()[0];
            if (record) {
            	editform.getForm().reset();
            	editform.getForm().findField('id').setValue(record.get('id'));
            	editform.getForm().findField('name').setValue(record.get('name'));
            	editform.getForm().findField('account').setValue(record.get('account'));
            	editform.getForm().findField('password').setValue(record.get('password'));
            	//formAdd.getForm().load(record);
    			Ext.getCmp('formmode').setValue('edit');
    			editwin.setTitle('修改');
    			editwin.show();
            	
            } else {
                alert('Please select a row from the grid');
            }
        }
    });
   
    var delAction = Ext.create('Ext.Action', {
		text: 'Delete',
        //icon   : '../shared/icons/fam/delete.gif',  // Use a URL in the icon config
        tooltip:'Remove the selected item',
		iconCls:'icon-delete',
        disabled: true,
        handler: function(widget, event) {				                 
				                var selModel = grid1.getSelectionModel();
				                if (selModel.hasSelection()) {
				                    Ext.Msg.confirm("警告", "确定要删除吗？",function (btn) {
				                        if (btn == 'yes') {
				                        	 var record = selModel.getSelection();
				                        	 //var jsonId = [];
				                        	 var jsonId = new Array();
				                        	 Ext.each(record, function(item) {
				                        	 jsonId.push(item.data['id']);
				                        	 });
				                        	 if (jsonId.length > 0) {
				                        	 Ext.Ajax.request({
				                        	 url: "deleteUser",
				                        	 params: { ids: Ext.JSON.encode(jsonId) },
				                        	 method: "POST",
				                        	 success: function(response) {
				                        	 Ext.Msg.alert("信息", "数据删除成功！");
				                        	 grid1.store.load();
				                        	 },
				                        	 failure: function(response) {
				                        	 Ext.Msg.alert("警告", "数据删除失败，请稍后再试！");
				                        	 }
				                        	});
										}
				                       }
				                    });
				                }
				                else {
				                        Ext.Msg.alert("错误", "没有任何行被选中，无法进行删除操作！");
				                     }
				       }
    });
   
   //数据展示grid
    var checkMode = Ext.create('Ext.selection.CheckboxModel');
    
    //右键菜单 
    var contextMenu = Ext.create('Ext.menu.Menu', {
          items: [
              addAction,
              updateAction,
              delAction
          ]
      });
    
	var grid1 = Ext.create('Ext.grid.Panel',{
		 title: '显示列表',
		 //region : "center",
		 region : "center",
         store:store,
         selModel: checkMode,
         trackMouseOver : false,
         loadMask: true,
         frame : true,
         stripeRows: true,
         //width:'100%',
         height:'auto',
         //layout:'fit',
         //height:435,
         //height:Ext.getCmp('mainTab').getActiveTab().getHeight()-100,
         //autoHeight : true,
         autoScroll:true,
         //forceFit: true,
         disableSelection : false, // 允许选择行 * 
        // selType : 'rowmodel',
		 columns: [		            
		            {header: 'id', dataIndex: 'id'},         
		            {header: 'name', dataIndex: 'name'},         
		            {header: 'account', dataIndex: 'account'},         
					{header: 'password', dataIndex: 'password', flex:1}
		           ], 
		 dockedItems: [{
				        xtype: 'pagingtoolbar', //分页 工具条 
				        store: store,   // same store GridPanel is using
				        dock: 'bottom',
				        iconCls: 'icon-grid',
				        displayInfo: true,
				        displayMsg: 'Displaying users {0} - {1} of {2}',
				        emptyMsg: "No users to display"
				      },
				      {
				        xtype: 'toolbar', //顶端 菜单
				        dock: 'top',
				        items: [addAction,'-',updateAction,'-',delAction]
				      }],
		   viewConfig: {
			   autoScroll:true,
            listeners: {
                itemcontextmenu: function(view, rec, node, index, e) {
                    e.stopEvent();
                    contextMenu.showAt(e.getXY());
                    return false;
                 }
               }
           }
           //anchor:'100% 80%',
		  });
 
	//grid监听双击事件 	
	grid1.addListener('itemdblclick',function(view, record, item,index, e, options){
	
		editform.getForm().reset();
		editform.getForm().loadRecord(record);
		//editform.getForm().load(record);
		Ext.getCmp('formmode').setValue('edit');
		editwin.setTitle('修改');
		editwin.show();
	});
    grid1.getSelectionModel().on({
        selectionchange: function(sm, selections) {
            if (selections.length) {
                updateAction.enable();
                delAction.enable();
            } else {
                updateAction.disable();
                delAction.disable();
            }
        }
    });
    
	//整体布局 
    Ext.create('Ext.Viewport',
    			{ 
				  border:false,
				  bodyStyle: 'padding:0px 0px 0px',
				  closable:true,//标签上出现关闭按钮
				  //layout:'anchor',
				  //autoScroll:true,
				  //heigh:557,
				  heigh:'auto',
				  //heigh:Ext.getCmp('mainTab').getActiveTab().getInnerHeight(),
				  //autoHeight : true,
				  renderTo: document.body,
				  layout: {
			            type: 'vbox',
			            align: 'stretch'  // Child items are stretched to full width
			        },
				  //renderTo:  'hello',
				  items: [/*{ 
							xtype:'panel',        
							//title: '查询条件',         
							//collapsible: true,
							//anchor:'100% 20%',
							//heigth:100,
							//layout:'fit',
							border:false,
							items :[formSearch,grid1]
						  }*/
				  		formSearch,
				        grid1
						 ]
	
				 });
									
});